//------------------------------------------------------------------------------
//  <copyright file="Polygon.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Geometry
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Robotics.Geometry;
    using Microsoft.Robotics.Numerics;

    /// <summary>
    /// Class representing a polygon.
    /// </summary>
    [DataContract]
    public class Polygon : GeometryElement2D
    {
        /// <summary>
        /// Points in the polygon
        /// </summary>
        [DataMember]
        private Point2D[] points;

        /// <summary>
        /// Line segments that make up the hull of the polygon
        /// </summary>
        [DataMember]
        private LineSegment2D[] hullLineSegments;

        /// <summary>
        /// A point outside the polygon.  Used for testing if another point is interior to polygon.
        /// </summary>
        [DataMember]
        private Point2D pointOutsidePolygon;

        /// <summary>
        /// Initializes a new instance of the <see cref="Polygon"/> class.
        /// </summary>
        /// <param name="polygonPoints">
        /// Ordered array of points defining the hull.  e.g. polygon is defined by drawing a straight line through points n and n+1 for
        /// every point, and then from the last point to the first.
        /// </param>
        public Polygon(Point2D[] polygonPoints)
        {
            if (polygonPoints.Length < 3)
            {
                throw new ArgumentException("A valid polygon must have at least three distinct points");
            }

            this.points = new Point2D[polygonPoints.Length];
            Array.Copy(polygonPoints, this.points, this.points.Length);

            if (!this.AreAllPointsUnique())
            {
                throw new ArgumentException("All points on polygon must be unique");
            }

            this.hullLineSegments = new LineSegment2D[this.NumPoints];

            double maxX = this.points[0].X;
            double maxY = this.points[0].Y;

            for (int i = 0; i < this.NumPoints - 1; ++i)
            {
                this.hullLineSegments[i] = new LineSegment2D(this.points[i], this.points[i + 1]);

                if (maxX < this.points[i].X)
                {
                    maxX = this.points[i].X;
                }

                if (maxY < this.points[i].Y)
                {
                    maxY = this.points[i].Y;
                }
            }

            this.hullLineSegments[this.NumPoints - 1] = new LineSegment2D(this.points[this.NumPoints - 1], this.points[0]);

            this.pointOutsidePolygon = new Point2D(maxX + 10, maxY + 10);

            if (!this.AreHullLineSegmentsNonIntersecting())
            {
                throw new ArgumentException("Line segments comprising hull must not intersect with any other segments except their neighbors");
            }
        }

        /// <summary>
        /// Gets the number of points that make up the polygon.
        /// </summary>
        [DataMember]
        public int NumPoints
        {
            get
            {
                return this.points.Length;
            }
        }

        /// <summary>
        /// Returns the indicated point in the polygon
        /// </summary>
        /// <param name="index">Index of point. </param>
        /// <returns>Point in the polygon.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Design",
            "CA1065:Do not raise exceptions in unexpected locations",
            Justification = "Normal for an indexer to raise an exception")]
        public Point2D this[int index]
        {
            get
            {
                if (index >= this.NumPoints || index < 0)
                {
                    throw new IndexOutOfRangeException();
                }

                return this.points[index];
            }
        }

        /// <summary>
        /// Compute the distance from another geometry element to the line
        /// </summary>
        /// <param name="e">A geometry element.</param>
        /// <returns>A distance.</returns>
        public override double DistanceFrom(GeometryElement2D e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Gets a (possibly empty) list of points at which two geometry elements intersect.
        /// Only indicates where intersections occur at discrete points between the hull, not area of elements, or 
        /// intersections that form something other than a point.
        /// </summary>
        /// <param name="e"> A geometry element.</param>
        /// <returns>A list of the distinct points at which the given geometry intersects this geometry.</returns>
        public override List<Point2D> GetIntersectionPoints(GeometryElement2D e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Gets a (possibly empty) list of non-point geometries at which two geometry elements intersects.
        /// Only indicates non-point intersections between the hulls of the geometries, not intersections of areas or
        /// intersections that occur at a point only.
        /// </summary>
        /// <param name="e"> A geometry element. </param>
        /// <returns>A list of the geometries describing the intersection of the two geometries excepting point intersections.</returns>
        public override List<GeometryElement2D> GetIntersectionGeometries(GeometryElement2D e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Gets a value indicating whether or not geometries intersect (without determining points or geometry of intersection).
        /// </summary>
        /// <param name="e">A 2D geometry element.</param>
        /// <returns>True if geometries intersect.</returns>
        public override bool Intersects(GeometryElement2D e)
        {
            if (e is Circle)
            {
                Circle circle = e as Circle;

                if (this.IsInterior(circle.Center))
                {
                    return true;
                }

                foreach (LineSegment2D segment in this.hullLineSegments)
                {
                    if (segment.GetIntersectionPoints(circle).Count > 0)
                    {
                        return true;
                    }
                }

                return false;
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Gets a value indicating if a point is interior to the polygon.
        /// </summary>
        /// <param name="point">A point.</param>
        /// <returns>True if the point is on the interior of the polygon.</returns>
        public bool IsInterior(Point2D point)
        {
            double testSegmentYAdjustment = 0;

            bool goodTest = false;

            LineSegment2D testSegment = new LineSegment2D(point, new Point2D(10000, 10000));

            while (!goodTest)
            {
                goodTest = true;

                // a little bit of a hack for now
                // need a better way to represent a ray at some point
                testSegment = new LineSegment2D(point, new Point2D(this.pointOutsidePolygon.X, this.pointOutsidePolygon.Y + testSegmentYAdjustment));

                // if we intersect any point directly the test will be indeterminate
                foreach (Point2D p in this.points)
                {
                    // if the test segment intersects a vertex directly, then that intersection
                    // will be double counted, so subtract one from the intersection count.
                    if (Math.Abs(testSegment.DistanceFrom(p)) < MathConstants.ErrorEpsilon)
                    {
                        goodTest = false;
                        testSegmentYAdjustment += 1;
                        break;
                    }
                }
            }

            int intersectionCount = 0;

            foreach (LineSegment2D segment in this.hullLineSegments)
            {
                if (segment.GetIntersectionPoints(testSegment).Count > 0)
                {
                    ++intersectionCount;
                }
            }

            if (intersectionCount % 2 == 0)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Check that all points on the polygon are unique
        /// </summary>
        /// <returns>True if all points on polygon are unique</returns>
        private bool AreAllPointsUnique()
        {
            for (int i = 0; i < this.NumPoints - 1; ++i)
            {
                for (int j = i + 1; j < this.NumPoints; ++j)
                {
                    if (this.points[i] == this.points[j])
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Check that the line segments of the hull do not intersect
        /// </summary>
        /// <returns>True if all hull line segments do not intersect</returns>
        private bool AreHullLineSegmentsNonIntersecting()
        {
            // need to check that no segment intersects with any segements except it's neighboring ones
            // first segment is a special case as we expect it to intersect with the last segment
            for (int j = 2; j < this.NumPoints - 1; ++j)
            {
                if (this.hullLineSegments[0].Intersects(this.hullLineSegments[j]))
                {
                    return false;
                }
            }

            for (int i = 1; i < this.NumPoints - 2; ++i)
            {
                for (int j = i + 2; j < this.NumPoints; ++j)
                {
                    if (this.hullLineSegments[i].Intersects(this.hullLineSegments[j]))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}
